<?php
namespace app\api\validate\wine;

use app\common\library\helper;
use think\Validate;

class Patient extends Validate{
    protected $rule =   [
        'name'  => 'require',
        'mobile'   => 'require',
        'idCard' => 'require',
        'birthday' => 'require',
        'sex' =>'require',
        'age' => 'require',
        'province' => 'require',
        'city' => 'require',
        'area' => 'require',
        'type_illness' => 'require',
        'remark' => 'require',
        'case' => 'require|checkCaseArr:json',

        'project_id' => 'require'
    ];

    protected $message  =   [
        'name.require'  => '缺少参数name',
        'mobile.require'   => '缺少参数mobile',
        'idCard.require' => '缺少参数idCard',
        'birthday.require' => '缺少参数birthday',
        'sex.require' =>'缺少参数sex',
        'age.require' => '缺少参数age',
        'height.require' => '缺少参数height',
        'weight.require' => '缺少参数weight',
        'province.require' => '缺少参数province',
        'city.require' => '缺少参数city',
        'area.require' => '缺少参数area',
        'type_illness.require' => '缺少参数type_illness',
        'case.require' => '缺少参数case',

        'project_id.require' => '缺少参数project_id',
        'remark.require' => '缺少参数remark'
    ];
    protected $scene = [
        'add'  =>  ['name','mobile','idCard','birthday','sex','age','province','city','area','type_illness','project_id','remark','case']
    ];

    // 验证json字符串
    protected function checkCaseArr($value, $rule, $data=[]){
        if($rule == 'json'){
            if(!is_string($value)){
                return 'case值必须为字符串';
            }
            $oldStr = htmlspecialchars_decode($value);
            if(empty($oldStr)){
                return 'case字符不能为空';
            }

            $arr = @json_decode((string)$oldStr, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return 'case字符串解析错误请检查';
            }
            // 校验格式
            if(!is_array($arr)){
                return 'case字符串解析后必须为数组';
            }
            foreach ($arr as $obj){
                if(!(isset($obj['uid']) && isset($obj['name']) && isset($obj['status']) && isset($obj['url']))){
                    return 'case字符串解析格式有误，需包含键值uid、name、status、url';
                }
                if($obj['status']!= 'done'){
                    return 'case字符串解析格式有误，status值错误';
                }
            }
            return true;
        }
        return 'case未定义解析规则';
    }
}
